/**
 * jims
 */
package com.jims.master.modules.finance.web;

import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.utils.DateUtils;
import com.jims.master.common.utils.NumberUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.BaseController;
import com.jims.master.modules.doctor.entity.ClinicMaster;
import com.jims.master.modules.doctor.entity.ClinicOrders;
import com.jims.master.modules.doctor.entity.ClinicOrdersCost;
import com.jims.master.modules.doctor.service.ClinicMasterService;
import com.jims.master.modules.doctor.service.ClinicOrdersCostService;
import com.jims.master.modules.doctor.service.ClinicOrdersService;
import com.jims.master.modules.finance.entity.OutpAcctMaster;
import com.jims.master.modules.finance.entity.OutpBillItems;
import com.jims.master.modules.finance.entity.OutpPaymentsMone;
import com.jims.master.modules.finance.entity.OutpRcptMaster;
import com.jims.master.modules.finance.service.OutpAcctMasterService;
import com.jims.master.modules.finance.service.OutpBillItemsService;
import com.jims.master.modules.finance.service.OutpPaymentsMoneService;
import com.jims.master.modules.finance.service.OutpRcptMasterService;
import com.jims.master.modules.med.service.MedicalCardConsumeMasterService;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.service.OrgDeptService;
import com.jims.master.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 门诊收费记录Controller
 * @author chentao
 * @version 2017-03-06
 */
@Controller
@RequestMapping(value = "${adminPath}/finance/outpRcptMaster")
public class OutpRcptMasterController extends BaseController {

	@Autowired
	private OutpRcptMasterService outpRcptMasterService;
	@Autowired
	private ClinicOrdersService  clinicOrdersService;
	@Autowired
	private ClinicOrdersCostService clinicOrdersCostService;
	@Autowired
	private OutpAcctMasterService outpAcctMasterService;
	@Autowired
	private OutpPaymentsMoneService outpPaymentsMoneService;
	@Autowired
	private OutpBillItemsService outpBillItemsService;
	@Autowired
	private ClinicMasterService clinicMasterService;
    @Autowired
    private OrgDeptService  orgDeptService;
    @Autowired
    private MedicalCardConsumeMasterService medicalCardConsumeMasterService;
	@ModelAttribute
	public OutpRcptMaster get(@RequestParam(required=false) String id) {
		OutpRcptMaster entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = outpRcptMasterService.get(id);
		}
		if (entity == null){
			entity = new OutpRcptMaster();
		}
		return entity;
	}

	/**
	 * 门诊收费页面--   if(isDoctor==0 || isOnlyCard){
	 * @param model
	 * @param clinicMaster
	 * @return String
	 * @author 赵宁
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = {"index", ""})
	public String list(ClinicMaster clinicMaster, Model model) {
 		if(clinicMaster.getClinicNo()!=null && clinicMaster.getClinicNo()!=""){
			clinicMaster=clinicMasterService.getMaster(clinicMaster.getClinicNo(),UserUtils.getOrgId());
 		}
        if(UserUtils.getUser().getOrgDept()!=null&&clinicMaster.getClinicAttr()!=null&&!"".equals(clinicMaster.getClinicAttr())){
             clinicMaster.setClinicAttr(orgDeptService.get(UserUtils.getUser().getOrgDept().getId()).getClinicAttr());
        }
        //
        if(clinicMaster.getClinicId()!=null&&!"".equals(clinicMaster.getClinicId())){
            clinicMaster.setClinicNo(clinicMasterService.get(clinicMaster.getClinicId()).getClinicNo());
        }
        model.addAttribute("clinicMaster",clinicMaster);
		return "modules/finance/outpCharge";
	}

	/**
	 * 查询费用主记录
	 * @param clinicNo
	 * @param clinicOrders
	 * @param model
	 * @param request
	 * @return String
	 * @author 赵宁
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = {"findCharge", ""})
    public String  findCharge(String clinicNo,ClinicOrders clinicOrders,Model model,HttpServletRequest request,
							  HttpServletResponse response){
		ClinicMaster clinicMaster = new ClinicMaster();
		Page<ClinicOrders> page= new Page<ClinicOrders>();
		clinicMaster.setClinicNo(clinicNo);
        clinicMaster = clinicMasterService.getMaster(clinicNo, UserUtils.getOrgId());
 		if(clinicMaster!=null){
            String code=outpRcptMasterService.preferentialCosts(clinicMaster.getChargeType(),clinicNo);
			if(code.equals("0")){
				clinicOrders.setClinicMaster(clinicMaster);
 				page=clinicOrdersService.findOrdersPage(new Page<ClinicOrders>(request, response), clinicOrders);
			}
		}
		model.addAttribute("page",page);
		model.addAttribute("clinicMaster",clinicMaster);
		return "modules/finance/chargeMaster";
	}

	/**
	 * 查询费用明细
	 *
	 * @param model
	 * @param clinicOrdersCost
	 * @return String
	 * @author 赵宁
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = {"findDetailCharge", ""})
	public String findDetailCharge(Model model,ClinicOrdersCost clinicOrdersCost,
								   HttpServletRequest request, HttpServletResponse response){
		Page<ClinicOrdersCost> page = new Page<>();
		 if(clinicOrdersCost.getOrdersId()!=null){
			 page=clinicOrdersCostService.findPage(new Page<ClinicOrdersCost>(request,response),clinicOrdersCost);
		 }
		 page.setPageSize(10);
		 model.addAttribute("clinicOrdersCost",clinicOrdersCost);
         model.addAttribute("page",page);
		return "modules/finance/chargeDetail";
	}

	/**
	 * 门诊收费记录页面
	 * @param outpRcptMaster
	 * @param request
	 * @param response
	 * @param model
	 * @return 陈涛
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = {"rcptIndex", ""})
	public String rcptList(OutpRcptMaster outpRcptMaster,String tollStartTime,String tollEndTime, HttpServletRequest request, HttpServletResponse response, Model model) {
		String orgId = UserUtils.getOrgId();
		outpRcptMaster.setOrgId(orgId);
		if (tollStartTime!=null||tollStartTime!=""){
			outpRcptMaster.setTollStartTime(tollStartTime);
		}
		if (tollEndTime!=null||tollEndTime!=""){
			outpRcptMaster.setTollEndTime(tollEndTime);
		}
		Page<OutpRcptMaster> page = outpRcptMasterService.findPage(new Page<OutpRcptMaster>(request, response), outpRcptMaster);
		model.addAttribute("page", page);
		return "modules/finance/outpRcptMasterIndex";
	}

	/**
	 * 门诊收费信息保存
	 * @param costs
	 * @param orderIds
	 * @param payType
     * @param cardNo 卡号
     * @param cardPayFlag 使用一卡通支付的标志 0 没有使用 1 使用
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "save")
	@ResponseBody
	public StringData save(String costs,String orderIds,String payType,String payMoney,
						   String totalMoney,String cardNo,String cardPayFlag,String serialNo) {
        if(serialNo==null || serialNo.equals("")){
			 serialNo = NumberUtils.getUUID();
		}
		StringData data=new StringData();
        Map<String,Object> map=outpRcptMasterService.save(costs,orderIds,payType,payMoney,totalMoney,cardNo,cardPayFlag,serialNo);
        String result= (String)map.get("result");
        if(StringUtils.isNotBlank(result) && result.equals("0")){
            data.setCode("success");
            data.setData(serialNo);
        }else{
            data.setCode("error");
            data.setData(serialNo);
        }
        return data;
	}

	/**
	 * 门诊结账
	 * @param startTime
	 * @param endTime
	 * @param model
	 * @return String
	 * @author 赵宁
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "outpAcct")
    public String  outpAcct(String startTime,String endTime,Model model){
		 User user=UserUtils.getUser();
		 user.setType("1");
         String acctNo=outpAcctMasterService.getMaxAcctNo();
		 String maxAcctDate = outpAcctMasterService.getMaxAcctDate(user);
         model.addAttribute("acctNo",acctNo);
		 if(maxAcctDate!=null && !"".equals(maxAcctDate)){
			  startTime= maxAcctDate;
		 }
		 if(endTime==null || endTime==""){
			   endTime=DateUtils.getDate("yyyy-MM-dd HH:mm:ss");
		 }
		 model.addAttribute("startTime",startTime);
		 model.addAttribute("endTime",endTime);
		 return "modules/finance/outpAcctIndex";
	}

	/**
	 * 结账主信息查询
	 * @param startTime
	 * @param endTime
	 * @param outpAcctMaster
	 * @param model
	 * @param request
	 * @param response
	 * @return String
	 * @author 赵宁
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "acctMaster")
    public String  acctMaster(String startTime,String endTime,OutpAcctMaster outpAcctMaster ,Model model,HttpServletRequest request,
							  HttpServletResponse response){
		outpAcctMaster.setCardFlag("0");
		outpAcctMaster.setCreateBy(UserUtils.getUser());
		outpAcctMaster.setStartTime(startTime);
		outpAcctMaster.setEndTime(endTime);
		OutpAcctMaster acctMaster = outpAcctMasterService.getAcctInfo(outpAcctMaster);
		List<OutpPaymentsMone> outpPaymentsMones= outpPaymentsMoneService.getPayments(outpAcctMaster);
		Page<OutpBillItems> page = outpBillItemsService.getBillItems(new Page<OutpBillItems>(request,response),outpAcctMaster);
		model.addAttribute("outpAcctMaster",acctMaster);
		model.addAttribute("payMents",outpPaymentsMones);
		model.addAttribute("page",page);
      return "/modules/finance/outpAcctMasterIndex";
	}

	/**
	 * 退费页面加载
	 * @param clinicNo
	 * @param model
	 * @param clinicMaster
	 * @return String
	 * @author 赵宁
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "refundCharges")
	public String refundCharges(String clinicNo,Model model,ClinicMaster clinicMaster){
		List<OutpRcptMaster> outpRcptMasters = new ArrayList<OutpRcptMaster>();
        if(clinicNo!=null && StringUtils.isNotBlank(clinicNo)){
             String orgID =UserUtils.getOrgId();
			 outpRcptMasters = outpRcptMasterService.getRcptInfo(clinicNo,orgID);
			 clinicMaster = clinicMasterService.getMaster(clinicNo,orgID);
		}
		model.addAttribute("rcptMaster",outpRcptMasters);
		model.addAttribute("clinicNo",clinicNo);
		model.addAttribute("clinicMaster",clinicMaster);
		return "/modules/finance/outpRefundCharge";
	}


	/**
	 * 查询收费明细(支付方式)
	 * @param model
	 * @return outpRcptMaster
	 * @author 赵宁
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "getBillItems")
	public String  getBillItems(OutpRcptMaster outpRcptMaster,Model model,
								HttpServletRequest request,HttpServletResponse response){
        Page<OutpBillItems> page=outpBillItemsService.findListItems(new Page<OutpBillItems>(request,response),outpRcptMaster.getId());
		List<OutpPaymentsMone> outpPaymentsMones= outpPaymentsMoneService.getPatmentsByRefund(outpRcptMaster);
		Double totalCosts =0.0;
		for(int i =0 ;i<outpPaymentsMones.size();i++){
			 totalCosts+=outpPaymentsMones.get(i).getCharges();
		}
		model.addAttribute("list",outpPaymentsMones);
		model.addAttribute("page",page);
		model.addAttribute("totalCost",totalCosts);
		return "/modules/finance/outpRefundRight";
	}

	/**
	 * 确认退费
	 * @param clinicNo
	 * @param rcptNos
	 * @return StringData
	 * @author 赵宁
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "confirmRefund")
	@ResponseBody
	public StringData confirmRefund(String clinicNo,String rcptNos,String  totalCosts,String serialNo,
									String cardNo,String moneyType,String payType,String payMoney){
      StringData data = new StringData();
      String code = outpRcptMasterService.conRefCharges(rcptNos,totalCosts,clinicNo,serialNo,cardNo,moneyType,payType,payMoney);
		if(StringUtils.isNotBlank(code) && code.equals("0")){
			data.setCode("success");
			data.setData("退费成功");
		}else{
			data.setCode("error");
			data.setData("退费成功");
		}
		return data;
	}
	/**
	 * 门诊收费记录查询
	 * @param model
	 * @param outpRcptMaster
	 * @param request
	 * @param response
	 * @return String
	 * @author 赵宁
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "searchRcptMaster")
	public String searchRcptMaster(Model model , OutpRcptMaster outpRcptMaster,HttpServletRequest request,HttpServletResponse response){
        if(!outpRcptMaster.isReadCard()){
            User user=UserUtils.getUser();
            outpRcptMaster.setCreateBy(user);
        }else{
             List<String> rcptNos=medicalCardConsumeMasterService.findByCardNo(outpRcptMaster.getCardNo());
             outpRcptMaster.setRcptNos(rcptNos);
        }
 		if(outpRcptMaster.getTollStartTime()==null||outpRcptMaster.getTollStartTime()==""){
			 outpRcptMaster.setTollStartTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		}
		if(outpRcptMaster.getTollEndTime()==null || outpRcptMaster.getTollEndTime()==""){
			 outpRcptMaster.setTollEndTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		}
		Page<OutpRcptMaster> page=outpRcptMasterService.findPage(new Page<OutpRcptMaster>(request,response),outpRcptMaster);
		model.addAttribute("page",page);
		model.addAttribute("outpRcptMaster",outpRcptMaster);
		return "/modules/finance/searchRcptMaster";
	}
	/**
	 * 门诊退费查询
	 * @param model
	 * @return String
	 * @author 赵宁
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "searchRefundCharges")
	public String searchRefundCharges(Model model,OutpRcptMaster outpRcptMaster,HttpServletRequest request ,
									  HttpServletResponse response){
        Page<OutpRcptMaster> page=outpRcptMasterService.findRefundCharges(new Page<OutpRcptMaster>(request, response), outpRcptMaster);
		model.addAttribute("page",page);
		model.addAttribute("outpRcptMaster",outpRcptMaster);
		return "/modules/finance/searchRefundCharges";
	}
    /**
     * 计算优惠
     * @param clinicNo  门诊号
     * @param chargeType 费别
     *                   @param ordersId
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "setCosts")
    @ResponseBody
    public StringData setCosts(String clinicNo,String chargeType,String ordersId) {
        StringData data=new StringData();
        String code=outpRcptMasterService.preferentialCosts(chargeType,clinicNo);
        if(code.equals("0")){
            data.setCode("success");
            data.setData(clinicOrdersService.get(ordersId).getCosts().toString());
        }else{
            data.setCode("error");
            data.setData("操作失败");
        }
        return data;
    }

	/**
	 * 门诊收费打印
	 * @param outpRcptMaster
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "printCharge")
	@ResponseBody
	public StringData printCharge(OutpRcptMaster outpRcptMaster){
        StringData stringData = new StringData();
	    String printPath = outpRcptMasterService.printCharges(outpRcptMaster);
		stringData.setCode("success");
		stringData.setData(printPath);
        return stringData;
	}
}